package com.jsy.seckill.mq.listener;

import com.jsy.common.vo.Result;
import com.jsy.pay.feign.WeixinPayFeign;
import com.jsy.seckill.pojo.SeckillOrder;
import com.jsy.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "${mq.pay.queue.seckilldlx}")
public class TimeoutPayMessageListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private WeixinPayFeign weixinPayFeign;
    /**
     * 秒杀订单延时支付处理
     * 1.关闭微信支付
     * 2.关闭失败，执行支付成功业务
     * 3.关闭成功，则执行支付失败业务
     * @param map
     */
    @RabbitHandler
    public void receiveMsg(Map<String,String> map) throws Exception {
        //获取秒杀订单ID
        String outTradeNo = map.get("outTradeNo");
        String username = map.get("username");
        //查询秒杀订单
        SeckillOrder seckillOrder = seckillOrderService.findSeckillOrderInRedis(outTradeNo);
        if (seckillOrder!=null){
            //如果为支付则关闭微信支付系统那边的订单，避免他人支付
            Result<Map<String, String>> mapResult = weixinPayFeign.closeOrder(outTradeNo);
            //获取微信关闭订单的结果
            Map<String, String> resultData = mapResult.getData();
            if (resultData!=null){
                //如果关闭时，被人支付了也算成功，成功的去处理订单
                seckillOrderService.saveOrderInRedisToDB(outTradeNo,"",username);
            }else {
                //如果关闭成功，则删除订单，回滚库存
                seckillOrderService.deleteOrder(outTradeNo,map.get("time"),username);
            }
        }
    }
}
